package com.sys.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sys.common.constant.Constant;
import com.sys.common.util.JwtUtil;
import com.sys.common.util.MD5Utils;
import com.sys.mapper.UserMapper;
import com.sys.mapper.UserRoleMapper;
import com.sys.pojo.Permission;
import com.sys.pojo.Role;
import com.sys.pojo.User;
import com.sys.pojo.UserRole;
import com.sys.service.RolePermissionService;
import com.sys.service.UserRoleService;
import com.sys.service.UserService;
import com.sys.vo.UserRoleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ZJF
 * @since 2021-04-01
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RolePermissionService rolePermissionService;

    @Override
    public Map login(User user) {
        if (!StringUtils.isEmpty(user.getUsername())) {
            if (!StringUtils.isEmpty(user.getPassword())) {
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getUsername, user.getUsername());
                User selectUser = userMapper.selectOne(queryWrapper);
                if (MD5Utils.verify(user.getPassword(), selectUser.getPassword())) {
                    JwtUtil jwtUtil = new JwtUtil();
                    Map<String, Object> chaim = new HashMap<>();
                    Integer id = selectUser.getId();
                    chaim.put("uId", id);
                    chaim.put("username", selectUser.getUsername());
                    String jwtToken = jwtUtil.encode(String.valueOf(selectUser.getId()), 1800000, chaim);
                    boolean verify = MD5Utils.verify(user.getPassword(), selectUser.getPassword());
                    HashMap<String, String> userMap = new HashMap<>();
                    if (verify) {
                        //获取用户角色
                        List<Role> roles = userRoleService.getAllRole(id);
                        //每个角色拥有的权限
                        List<Permission> rolePermission = rolePermissionService.getRolePermissionPerms(roles);
                        ArrayList<String> perms = new ArrayList<>();
                        for (Permission permission : rolePermission) {
                            perms.add(permission.getPerms());
                        }
                        userMap.put("token", jwtToken);
                        userMap.put("username", selectUser.getUsername());
                        userMap.put("uId", String.valueOf(selectUser.getId()));
                        userMap.put("perms", perms.toString());
                        return userMap;
                    } else {
                        return null;
                    }
                } else {
                    return null;
                }
            } else {
                log.error("密码不能为空");
                return null;
            }
        } else {
            log.error("输入账号不能为空");
            return null;
        }
    }

    @Override
    public IPage<User> findListByPage(User user) {
        IPage<User> iPage = new Page<>(user.getPage(), user.getLimit());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(User::getDeleted, Constant.DELETED);
        queryWrapper.select(User::getUsername, User::getId, User::getCreateTime, User::getDeleted, User::getStatus);
        if (!StringUtils.isEmpty(user.getUsername())) {
            queryWrapper.like(User::getUsername, user.getUsername());
        }
        return userMapper.selectPage(iPage, queryWrapper);
    }

    @Override
    public int add(User user) {
        user.setDeleted(Constant.UNDELETED);
        String salt = MD5Utils.getSalt();
        String generate = MD5Utils.generate(user.getPassword(), salt);
        user.setPassword(generate);
        user.setSalet(salt);
        return userMapper.insert(user);
    }

    @Override
    public int delete(Integer id) {
        User user = new User();
        user.setId(id);
        user.setDeleted(Constant.DELETED);
        return userMapper.updateById(user);
    }

    @Override
    public int updateData(User user) {
        if (!StringUtils.isEmpty(user.getPassword())) {
            String salt = MD5Utils.getSalt();
            String generate = MD5Utils.generate(user.getPassword(), salt);
            user.setPassword(generate);
            user.setSalet(salt);
            userMapper.updateById(user);
        } else {
            user.setPassword(null);
            userMapper.updateById(user);
        }
        return userMapper.updateById(user);
    }

    @Override

    @Transactional(rollbackFor = Exception.class)
    public boolean relationRole(UserRoleVo vo) {
        List<Integer> rId = vo.getrId();
        int n = rId.size();
        int m = 0;
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, vo.getuId());
        userRoleMapper.delete(queryWrapper);
        for (Integer rid : rId) {
            UserRole userRole = new UserRole();
            userRole.setUserId(vo.getuId());
            userRole.setRoleId(rid);
            m += userRoleMapper.insert(userRole);
        }
        if (m == n) {
            return true;
        } else {
            return false;
        }
    }

}
